package com.igeek.config.ch02.log;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
@Aspect
@Order(2)
public class LogAspect {

    @Before("execution(* ICount.*(..))")
    public void beforeAdvice(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        System.out.println("日志追踪 The method "+methodName+" begin with "+ Arrays.toString(args));
    }

    @After("execution(* ICount.*(..))")
    public void afterAdvice(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();

        System.out.println("日志追踪 The method "+methodName+"end with");
    }

    @AfterReturning(value = "execution(* ICount.*(..))",returning = "result")
    public void returnAdvice(JoinPoint joinPoint,Object result){
        System.out.println("日志追踪 The method "+joinPoint.getSignature().getName()+"end with"+result);
    }

    @AfterThrowing(value = "execution(* ICount.*(..))",throwing = "ex")
    public void throwAdvice(JoinPoint joinPoint,Throwable ex){
        System.out.println("日志追踪 The method "+joinPoint.getSignature().getName()+"end with"+ex.getMessage());
    }

    @Around("execution(* ICount.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint pjp){
        String methodName = pjp.getSignature().getName();
        Object[] args = pjp.getArgs();
        Object result =null;
        try {
            System.out.println("@Around 日志追踪 The Method"+methodName+"begin with"+Arrays.toString(args));
            result=pjp.proceed();
            System.out.println("@Around 日志追踪 The Method"+methodName+"end with"+result);

        } catch (Throwable throwable) {
            System.out.println("@Around 日志追踪 The Method"+methodName+"发生异常"+throwable.getMessage());
            throwable.printStackTrace();
        }
        System.out.println("@Around 日志追踪 The Method"+methodName+"end with");
        return  result;
    }
}
